import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:horizontal_data_table/horizontal_data_table.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/tongjichaxun/RightEndDrawer.dart';
import 'package:jyofservice/bean/gongdan_list_entity.dart';
import 'package:jyofservice/util/Constants.dart';
import 'package:jyofservice/util/TongJiEvent.dart';
import 'dart:async';
import 'package:intl/intl.dart';

class LeiXinTongJiPage extends StatefulWidget {

  final String? titleName;
  LeiXinTongJiPage({this.titleName});

  @override
  _LeiXinTongJiPageState createState() => _LeiXinTongJiPageState();
}

class _LeiXinTongJiPageState extends State<LeiXinTongJiPage> {

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
  List<GongdanListData> tongjiListData = [];
  ScrollController scrollController = ScrollController();
  String? _startTime;
  String? _endTime;
  String? _departId;

  //eventBus通信
  StreamSubscription? subscriptionType = null;

  Color color1 = Color(0xFFFFFFFF);
  Color color2 = Color(0xFFEEEEEE);

  bool isloading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _startTime = DateFormat("yyyy-MM-dd").format(DateTime.now()).toString()+" "+"00:00:00";
    _endTime = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now()).toString();

    //获取数据
    getGongDanLeiXinTongJiData();

    subscriptionType =  Constants.eventBus.on<TongJiEvent>().listen((event) {

      if(event.type.toString() == widget.titleName) {

        print("工单类型统计${event.startTime}---${event.endTime}");

        if (mounted) {
          setState(() {

            isloading = false;
            _startTime = event.startTime;
            _endTime = event.endTime;
            _departId = event.departmentId;

            getGongDanLeiXinTongJiData();
          });
        }

      }

    });

    subscriptionType!.resume();

  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    subscriptionType!.cancel();

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(

      key: _scaffoldKey,
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.titleName!,style: TextStyle(
            color: Colors.white, fontSize: ScreenUtil().setSp(45)),),
        elevation: 0.0,
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios),
            onPressed: () {
              Navigator.pop(context, false);
            }),
      ),
      body: Stack(
        children: <Widget>[

          HorizontalDataTable(
            leftHandSideColumnWidth: 100,
            rightHandSideColumnWidth: 3100,
            isFixedHeader: true,
            headerWidgets: _getTitleWidget(),
            leftSideItemBuilder: _generateFirstColumnRow,
            rightSideItemBuilder: _generateRightHandSideColumnRow,
            itemCount: tongjiListData.length,
            rowSeparatorWidget: const Divider(
              color: Colors.black54,
              height: 1.0,
              thickness: 0.0,
            ),
            leftHandSideColBackgroundColor: Color(0xFFFFFFFF),
            rightHandSideColBackgroundColor: Color(0xFFFFFFFF),
          ),
          Offstage(
            offstage: isloading,
            child: SpinKitFadingCircle(
              color: Colors.blue,
              size: 50.0,
            ),
          )
        ],
      ),

      endDrawer: RightEndDrawer(type: widget.titleName,isOffstage: false,),
    );
  }

  //通话记录视图
  List<Widget> _getTitleWidget() {
    return [
      _getTitleItemWidget('责任单位', 100),
      _getTitleItemWidget('处理部门', 100),
      _getTitleItemWidget('表单总数', 100),
      _getTitleItemWidget('已完成', 100),
      _getTitleItemWidget('未完成', 100),
      _getTitleItemWidget('缓办', 100),
      _getTitleItemWidget('室内不热', 100),
      _getTitleItemWidget('不热登记', 100),
      _getTitleItemWidget('外管网漏水', 100),
      _getTitleItemWidget('楼栋漏水', 100),
      _getTitleItemWidget('单元漏水', 100),
      _getTitleItemWidget('室内漏水', 100),
      _getTitleItemWidget('更换锁闭阀', 100),
      _getTitleItemWidget('开/关阀门', 100),
      _getTitleItemWidget('青镇-漏水', 100),
      _getTitleItemWidget('青镇-不热', 100),
      _getTitleItemWidget('其它报修', 100),
      _getTitleItemWidget('农饮-水压小', 100),
      _getTitleItemWidget('外管网漏水', 100),
      _getTitleItemWidget('楼栋漏水', 100),
      _getTitleItemWidget('其他报修', 100),
      _getTitleItemWidget('单元漏水', 100),
      _getTitleItemWidget('室内漏水', 100),
      _getTitleItemWidget('更换配件', 100),
      _getTitleItemWidget('开/关阀门', 100),
      _getTitleItemWidget('水压小', 100),
      _getTitleItemWidget('家中没水', 100),
      _getTitleItemWidget('井盖破损', 100),
      _getTitleItemWidget('农饮-新接水', 100),
      _getTitleItemWidget('农饮-漏水', 100),
      _getTitleItemWidget('农饮-开/关阀', 100),
      _getTitleItemWidget('农饮-停水', 100),

    ];
  }

  Widget _getTitleItemWidget(String label, double width) {
    return Container(
      child: Text(label, style: TextStyle(fontWeight: FontWeight.bold)),
      width: width,
      height: 56,
      padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
      alignment: Alignment.centerLeft,
    );
  }

  //第一列数据
  Widget _generateFirstColumnRow(BuildContext context, int index) {

    Color _color = tongjiListData[index].departmentName=="合计"?Colors.redAccent:
    tongjiListData[index].departmentName=="小计"?Colors.orange:
    (index % 2 == 0) ? color1 : color2;

    return Container(
      color: _color,
      child: Text(tongjiListData[index].parentName??""),
      width: 200,
      height: 52,
      padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
      alignment: Alignment.centerLeft,
    );
  }

  //其他列数据
  Widget _generateRightHandSideColumnRow(BuildContext context, int index) {

    Color _color = tongjiListData[index].departmentName=="合计"?Colors.redAccent:
    tongjiListData[index].departmentName=="小计"?Colors.orange:
    (index % 2 == 0) ? color1 : color2;

    return Row(
      children: <Widget>[
        containerItem(tongjiListData[index].departmentName??"",_color),
        containerItem(tongjiListData[index].zs??"",_color),
        containerItem(tongjiListData[index].ywc??"",_color),
        containerItem(tongjiListData[index].wwc??"",_color),
        containerItem(tongjiListData[index].wwchb??"",_color),
        containerItem(tongjiListData[index].g1??"",_color),
        containerItem(tongjiListData[index].g26??"",_color),
        containerItem(tongjiListData[index].g2??"",_color),
        containerItem(tongjiListData[index].g3??"",_color),
        containerItem(tongjiListData[index].g4??"",_color),
        containerItem(tongjiListData[index].g5??"",_color),
        containerItem(tongjiListData[index].g6??"",_color),
        containerItem(tongjiListData[index].g7??"",_color),
        containerItem(tongjiListData[index].g8??"",_color),
        containerItem(tongjiListData[index].g9??"",_color),
        containerItem(tongjiListData[index].g10??"",_color),
        containerItem(tongjiListData[index].g23??"",_color),
        containerItem(tongjiListData[index].g11??"",_color),
        containerItem(tongjiListData[index].g12??"",_color),
        containerItem(tongjiListData[index].g24??"",_color),
        containerItem(tongjiListData[index].g13??"",_color),
        containerItem(tongjiListData[index].g14??"",_color),
        containerItem(tongjiListData[index].g15??"",_color),
        containerItem(tongjiListData[index].g16??"",_color),
        containerItem(tongjiListData[index].g17??"",_color),
        containerItem(tongjiListData[index].g18??"",_color),
        containerItem(tongjiListData[index].g19??"",_color),
        containerItem(tongjiListData[index].g25??"",_color),
        containerItem(tongjiListData[index].g20??"",_color),
        containerItem(tongjiListData[index].g21??"",_color),
        containerItem(tongjiListData[index].g22??"",_color),
      ],
    );
  }

  Widget containerItem(dynamic _text,Color _color) {

    return  Container(
      color: _color,
      child: Text(_text.toString()),
      width: 100,
      height: 52,
      padding: EdgeInsets.fromLTRB(5, 0, 0, 0),
      alignment: Alignment.centerLeft,
    );
  }

  Future getGongDanLeiXinTongJiData() async{

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String? key = sharedPreferences.getString("key");
    print("工单类型统计key===$key");
    String aesData= await AesUtil.encodeBase64();
    var data = {
      "key": key,
      "BeginDt":_startTime,
      "EndDt": _endTime,
      "Department_id":_departId??"",
      "ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "Statistics/GetGONGDANTONGJI",
        data: data);

    print("${WebConfig().baseUrl + "Statistics/GetGONGDANTONGJI"}");
    print("工单类型统计:${response}==$data");

    if (response.data["Code"] == "200") {

      if(response.data["Data"].length>0) {

        tongjiListData.clear();

        for (int i = 0; i < response.data["Data"].length; i++) {
          GongdanListData gongdanListEntity =
          new GongdanListData.fromJson(response.data["Data"][i]);
          tongjiListData.add(gongdanListEntity);
        }
      } else {

        Fluttertoast.showToast(

          msg: "未查询到数据",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,

        );

      }

      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
    } else {
      if (mounted) {
        setState(() {
          isloading = true;
        });
      }
      Fluttertoast.showToast(msg: "当前请求数据错误请重新刷新");
    }
  }

}
